/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-10-08 13:53:56
 * @LastEditTime : 2024-02-04 17:56:35
 */
import {
  Provide,
  Inject,
  Get,
  Post,
  Query,
  Config,
  Body,
} from '@midwayjs/decorator';
import {
  CoolController,
  BaseController,
  CoolEps,
  TagTypes,
  CoolUrlTag,
  CoolTag,
} from '@cool-midway/core';
import { Context } from '@midwayjs/koa';
import { Context as SocketContext } from '@midwayjs/socketio';
import { CoolFile } from '@cool-midway/file';
import { BaseSysParamService } from '../../service/sys/param';
import { FileService } from '../../../files/service/file';
import { SocketManagerService } from '../../../../socket/socket.service';
import * as jwt from 'jsonwebtoken';
import { buildUUID } from '../../../../comm/uuid';
import { useWxyy } from '../../../../comm/wxyy';

const core_1 = require('@cool-midway/core');
const moment = require('moment');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
/**
 * 不需要登录的后台接口
 */
@CoolUrlTag()
@Provide()
@CoolController()
export class BaseAppCommController extends BaseController {
  @Inject()
  coolFile: CoolFile;

  @Inject()
  ctx: Context;

  @Inject()
  eps: CoolEps;

  @Config('module.base')
  jwtConfig;

  @Inject()
  baseSysParamService: BaseSysParamService;

  @Inject()
  fileService: FileService;

  @Inject()
  socketManagerService: SocketManagerService;

  @Get('/param', { summary: '参数配置' })
  async param(@Query('key') key: string) {
    return this.ok(await this.baseSysParamService.dataByKey(key));
  }

  /**
   * 实体信息与路径
   * @returns
   */
  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/eps', { summary: '实体信息与路径' })
  public async getEps() {
    return this.ok(this.eps.app);
  }

  /**
   * 文件上传
   */
  @Post('/upload', { summary: '文件上传' })
  async upload() {
    const { fields, files } = this.ctx;
    const getPath = () => {
      try {
        const { dir, filename } = fields;
        if (_.isEmpty(files)) {
          throw new core_1.CoolCommException('上传文件为空');
        }
        const file = files[0];
        const extension = (filename || file.filename).split('.').pop();
        const uuname = `${buildUUID()}__${filename || file.filename}`;
        const name =
          (dir || moment().format('YYYYMMDD')) +
          '/' +
          (uuname || `${buildUUID()}.${extension}`);
        const target = path.join(
          this.baseApp.getBaseDir(),
          '..',
          `public/uploads/${name}`
        );
        const dirPath = path.join(
          this.baseApp.getBaseDir(),
          '..',
          `public/uploads/${dir || moment().format('YYYYMMDD')}`
        );
        if (!fs.existsSync(dirPath)) {
          fs.mkdirSync(dirPath, { recursive: true });
        }
        const data = fs.readFileSync(file.data);
        fs.writeFileSync(target, data);
        return {
          path: `/public/uploads/${name}`,
          fullPath: `${
            this.baseApp.getConfig().cool.file.domain
          }/public/uploads/${name}`,
        };
      } catch (err) {
        // this.coreLogger.error(err);
        throw new core_1.CoolCommException('上传失败');
      }
    };
    const { path: fpath, fullPath } = await getPath();
    return this.ok({
      path: fpath,
      fullPath,
    });
  }

  /**
   * 文件上传模式，本地或者云存储
   */
  @Get('/uploadMode', { summary: '文件上传模式' })
  async uploadMode() {
    return this.ok(await this.coolFile.getMode());
  }

  @Post('/screen/file/add')
  async saveScreenFile(@Body() body) {
    const token = this.ctx.get('Authorization');
    const info = jwt.verify(token, this.jwtConfig.jwt.secret);
    let data: any = {};
    try {
      data = {
        ...body,
        fileName: `${buildUUID()}${body?.fileName}`,
        mixFileName: body.path.substring(body.path.lastIndexOf('/') + 1),
        userName: info?.username,
        userId: info?.userId,
      };
      this.fileService.saveProjectFile(data);
    } catch (error) {
      console.log('error: ', error);
    }
    return this.ok(data);
  }

  @Post('/chat/create/chart')
  async chatWxyyChart(@Body() body) {
    const res = await useWxyy(body.message);
    return this.ok(res);
  }

  @Post('/message/send')
  async sendMessage(@Body() body) {
    // this.notification.sendMessage(body);
    this.socketManagerService.sendMessageToAll('哈哈哈');
  }
}
